package com.library.relation.dao;

import com.framework.BaseDao;
import com.library.entity.Book;
import com.library.entity.BookRelation;
import com.library.entity.Staff;
import com.library.entity.StaffRelation;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class BookRelationDaoImpl extends BaseDao<BookRelation,String> {
	@Resource
	private SessionFactory sessionFactory;

	public List<BookRelation> findByBook(Book book){
		try{
			return super.findByProperty("from BookRelation br where br.bookOne=? or br.bookTwo=?", new Object[]{book,book});
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	public List<BookRelation> findByBookOrderByCountDesc(Book book){
		Object[] params = new Object[]{book};
		String hql = "from BookRelation br where br.bookOne=? and br.bookOne != br.bookTwo order by br.count desc";
		Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
		query.setMaxResults(3);	//最大查询为3

		if (params != null && params.length > 0) {
			for (int i = 0; i < params.length; i++) {
				query.setParameter(i, params[i]);
			}
		}

		return query.list();
	}

	public BookRelation findByBookAndBook(Book b1, Book b2){
		try{
			return super.findOne("from BookRelation br where br.bookOne=? and br.bookTwo=?", new Object[]{b1,b2});
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	public BookRelation getRelationById(Integer relationId){
		try{
			return super.get(relationId);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	public void saveRelation(BookRelation relation){
		try {
			this.save(relation);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void updateRelation(BookRelation relation){
		try {
			this.update(relation);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public List<BookRelation> getAll(){
		try{
			return super.findByProperty("from BookRelation", new Object[]{});
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	public void deleteRelation(BookRelation relation){
		try {
			this.delete(relation);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
